package de.joergviola.mobj.client.database;

import java.io.Serializable;
import java.util.Arrays;
import java.util.logging.Logger;

import com.google.code.gwt.database.client.SQLTransaction;

import de.joergviola.mobj.shared.Entity;
import de.joergviola.mobj.shared.Schema;
import de.joergviola.mobj.shared.UnknownEntityException;

public class Insert<T extends Serializable> {

	private static final Logger log = Logger.getLogger("Insert");
	private final Entity<T> entity;
	private final T t;
	private Schema schema;

	public Insert(Schema schema, Entity<T> entity, T t) {
		this.schema = schema;
		this.entity = entity;
		this.t = t;
	}

	public void execute(SQLTransaction tx) throws UnknownEntityException {
		String sql = getSQL();
		Object[] args = getArgs(t, tx);
		log.info(sql + " : " + Arrays.toString(args));
		tx.executeSql(sql, args);
	}

	public String getSQL() {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO ");
		sql.append(entity.getEntityName());
		sql.append("(");
		String[] fieldnames = entity.getFieldnames();
		for (int i = 0; i < fieldnames.length; i++) {
			if (i > 0)
				sql.append(",");
			sql.append(fieldnames[i]);
		}
		sql.append(") VALUES (");
		for (int i = 0; i < fieldnames.length; i++) {
			if (i > 0)
				sql.append(",");
			sql.append("?");
		}
		sql.append(")");
		return sql.toString();
	}

	public Object[] getArgs(T t, SQLTransaction tx)
			throws UnknownEntityException {
		DBEntityWriter writer = new DBEntityWriter(schema, tx,
				entity.getFieldnames());
		entity.getValues(t, writer);
		return writer.getArgs();
	}

}
